package com.fourthGroup.mq;

import com.fourthGroup.service.CouponService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.function.Consumer;

@Component
@Slf4j
public class CouponConsumer {

    @Autowired
    private CouponService couponService;

    /**
     * 消费抢购优惠券消息
     */
    @Bean
    public Consumer<Message<Map<String, Object>>> grabCoupon() {
        return message -> {
            Map<String, Object> payload = message.getPayload();
            Integer userId = (Integer) payload.get("userId");
            Long couponId = Long.valueOf(payload.get("couponId").toString());
            
            log.info("收到抢购优惠券消息: userId={}, couponId={}", userId, couponId);
            
            try {
                couponService.processGrabCoupon(userId, couponId);
            } catch (Exception e) {
                log.error("处理抢购优惠券消息异常: ", e);
            }
        };
    }
} 